package juc;

/**
 * @Author linhao
 * @Date created in 11:19 上午 2021/3/28
 */
public class SynchronizedWarrper {

    private volatile Object value;

    private final Object mutex;

    public Object getValue(){
        return value;
    }

    public SynchronizedWarrper(Object value) {
        this.mutex = this;
        this.value = value;
    }

    private boolean checkNotNull(Object value) {
        return value != null;
    }

    public boolean decrease(){
        synchronized (mutex){
            if(value instanceof Integer){
                Integer temp = (Integer) value;
                if(temp == 0){
                    return false;
                }
                temp = temp -1;
                value = temp;
                return true;
            }
            return false;
        }
    }

    public boolean update(Object newValue) {
        synchronized (mutex) {
            if(!checkNotNull(newValue)){
                return false;
            }
            this.value = newValue;
            return true;
        }
    }

    public boolean clear() {
        synchronized (mutex) {
            if(!checkNotNull(value)){
                return false;
            }
            this.value = null;
            return true;
        }
    }

    public Object read() {
        synchronized (mutex) {
            return value;
        }
    }
}
